package stream;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import org.testng.annotations.Test;

/**
 * @author zhang peipei
 *
 * reduce
 * t1:
 * t2: 生成空list空指针
 *
 */
public class Stream2 {


    @Test
    public void t1() {
        var map = new HashMap<String, Integer>();
        map.put("a", 1);
        map.put("b", 1);
        map.put("c", 1);



        Optional<String> reduceKey = map.keySet().stream().reduce(((entry, entry2) -> entry + entry2));
        // Optional[abc]，说明并不是两两分组再处理，而是从处理的结果的基础上持续处理
        System.out.println(reduceKey);

        map.put("d", 1);
        map.put("e", 1);
        Optional<String> reduce2 = map.keySet().stream().reduce(((entry, entry2) -> entry + entry2));
        System.out.println(reduce2);

    }

    @Test
    private void t2() {
        var set = new HashSet<>();
        // 不会报错
        set.stream()
            .collect(Collectors.toList());

        HashSet set2 = null;
        set2.stream()   // 该行报错
            .collect(Collectors.toList());

    }

    @Test
    public  void t3() {
        var set = new HashSet<>();
        set.add(null);

        Object collect = set.stream()
                .map(list -> returnNull(list))
                .flatMap(Collection::stream)
                .collect(Collectors.toList());
    }


    private List returnNull(Object o) {
        return null;
    }
}
